<?php

namespace app\api\controller;

use app\data\controller\api\Auth;
use app\data\model\DataEnterpriseExtension;
use app\data\model\DataPolicyExtension;
use app\data\model\DataQiyeRzinfo;
use app\data\model\DataQiyeXinxiku;
use app\data\model\DataUserReview;
use app\data\model\DataZhengceku;
use app\data\model\PolicyBasics;
use app\data\model\RecruitmentTalent;
use app\data\service\UserAdminService;
use app\data\service\UserTokenService;
use think\Exception;
use think\facade\Db;

class User extends Auth
{

    //生成新token
    public function setToekn()
    {
        UserTokenService::token($this->uuid, 'wxapp');
        return_msg(200, '生成成功', UserAdminService::get($this->uuid, 'wxapp'));
    }


    //获取用户信息
    public function getUserinfo()
    {
        $info = Db::name('data_user')->where('id', $this->uuid)->field('id,phone,headimg,nickname,email,dizhi,gsmc,zhiwei')->find();
        return_msg(200, '查询成功', $info);
    }


    //更新个人信息
    public function updateUserInfo()
    {
        $nickname = input('nickname');
        $avatar   = input('headimg');
        $mobile   = input('phone');
        $email    = input('email');
        $dizhi    = input('dizhi');
        $gsmc     = input('gsmc');
        $zhiwei   = input('zhiwei');
        if (!empty($nickname)) {
            $data['nickname'] = $nickname;
        }
        if (!empty($avatar)) {
            $data['headimg'] = $avatar;
        }
        if (!empty($mobile)) {
            $data['phone'] = $mobile;
        }
        if (!empty($email)) {
            $data['email'] = $email;
        }
        if (!empty($dizhi)) {
            $data['dizhi'] = $dizhi;
        }
        if (!empty($gsmc)) {
            $data['gsmc'] = $gsmc;
        }
        if (!empty($zhiwei)) {
            $data['zhiwei'] = $zhiwei;
        }
        Db::startTrans();
        try {

            Db::name('data_user')->where('id', $this->uuid)->update($data);
            Db::commit();
            return_msg(200, '更新成功');
        }
        catch (Exception $e) {

            Db::rollback();
            return_error('操作失败');
        }
    }

    /**
     * 用户关联的企业信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function enterprise()
    {
        //获取用户所关联的企业信息
        $enterpriseIds  = DataQiyeRzinfo::query()
            ->where('status', 1)
            ->where('deleted', 0)
            ->where('user_id', $this->uuid)
            ->column('qrxxk_id');
        $enterpriseList = DataQiyeXinxiku::query()->field(['id', 'qymc'])->whereIn('id', $enterpriseIds)->select();
        return_msg(200, '查询成功', ['list' => $enterpriseList]);
    }

    /**
     * 获取用户发布的招聘数量和近30天的查看人才数量
     */
    public function positionsNum()
    {
        $num       = RecruitmentTalent::query()->where('poster', $this->uuid)->count();
        $talentNum = DataUserReview::query()
            ->where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-30 days')))
            ->where('ob_user', $this->uuid)->count();
        return_msg(200, '查询成功', ['position_num' => $num ?? 0, 'talent_num' => $talentNum ?? 0]);
    }

    /**
     * 谁看过我
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function viewList()
    {
        $enterpriseIds = DataUserReview::query()->where('user_id', $this->uuid)->column('enterprise_id');
        if (!$enterpriseIds) {
            return_msg(200, '查询成功', []);
        }
        $list = DataQiyeXinxiku::query()->whereIn('id', $enterpriseIds)->select();
        return_msg(200, '查询成功', $list ?? []);
    }

    public function matchingPolicy()
    {
        $userId = 1;
        /**
         * @var $userEnterprise DataQiyeRzinfo
         * @var $enterprise     DataQiyeXinxiku
         */
        $userEnterprise = DataQiyeRzinfo::query()->where('user_id', $userId)->where('status', 1)->where('deleted', 0)->order('id', 'desc')->find();
        if (!$userEnterprise) {
            return_msg(400, '用户未认证企业', []);
        }
        $enterprise = DataQiyeXinxiku::query()->where('id', $userEnterprise->qrxxk_id)->find();
        if (!$enterprise) {
            return_msg(404, '用户绑定企业不存在', []);
        }
        $enterpriseExtension = DataEnterpriseExtension::query()
            ->where('enterprise_id', $enterprise->id)
            ->where('status', '=', 1)
            ->where('value', '>', '0')
            ->whereNotNull('value')
            ->select()->toArray();

        $list = [];
        if ($enterpriseExtension) {
            $policyExtension = DataPolicyExtension::query();
            foreach ($enterpriseExtension as $item) {
                $policyExtension = $policyExtension->where('policy_information_type', $item['policy_information_type'])
                    ->whereFindInSet('id_set', $item['value']);
            }
            $policyExtension = $policyExtension->select()->toArray();
            $policyIds       = array_column($policyExtension, 'policy_id');
            $policyIds       = array_unique($policyIds);
            sort($policyIds);
            $list = DataZhengceku::query()->whereIn('id', $policyIds)->select()->toArray();
        }
        //匹配企业标签
        $tags = $enterprise->qybq ? explode(',', $enterprise->qybq) : [];

        $tagEnterprise = [];
        if ($tags) {
            $tagEnterprise = DataZhengceku::query()->where(function ($query) use ($tags)
            {
                foreach ($tags as $tag) {
                    $query->whereOrRaw("FIND_IN_SET(?,`qybq`)", [$tag]);
                }
            })->select()->toArray();
        }
        //匹配扩展字段的企业信息
        $list = array_merge($list, $tagEnterprise);
        foreach ($list as &$item) {
            if (!empty($item['admin_id'])) {
                $item['admin_name'] = Db::name("system_user")->where('id', $item['admin_id'])->value('nickname');
            } else {
                $item['admin_name'] = '-';
            }
            $item['sbksrq_txt'] = $item['sbksrq'] ? date('Y-m-d', $item['sbksrq']) : '';
            $item['ctrq_txt']   = $item['ctrq'] ? date('Y-m-d', $item['ctrq']) : '';
            if ($item['riqitype'] == 1) {
                if (!empty($item['sbjzrq'])) {
                    if ($item['sbjzrq'] > time()) {
                        // 计算剩余秒数
                        $remainingSeconds = $item['sbjzrq'] - time();
                        if ($remainingSeconds >= 86400) { // 大于等于 1 天
                            // 计算剩余天数
                            $remainingDays = floor($remainingSeconds / 86400);
                            $item['syts']  = $remainingDays . '天';
                        } else {
                            // 小于 1 天，计算剩余小时数
                            $remainingHours = floor($remainingSeconds / 3600);
                            $item['syts']   = $remainingHours . '小时';
                        }
                    } else {
                        $item['syts'] = '已结束';
                    }
                } else {
                    $item['syts'] = '-';
                }
            } else {
                $item['syts'] = '长期';
            }
            $item['level_name'] = PolicyBasics::RELEASE_LEVEL_MAP[$item['level_id']] ?? '-';
        }
        unset($item);
        return_msg(200, '查询成功', $list);
    }
}
